package cn.com.jslh.boarpro.main.presenter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.load.engine.Resource;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimAdapterEx;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.base.mvp.BasePresenterImpl;
import cn.com.jslh.boarpro.main.contract.RecordTemplateContract;
import cn.com.jslh.boarpro.main.model.RecordTemplateModelImpl;
import cn.com.jslh.boarpro.util.JSONUtil;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.database.DataBaseUtil;
import cn.com.jslh.boarpro.util.template.BaseAction;
import cn.com.jslh.boarpro.util.template.TemplateHelper;

/**
 * Created by Administrator on 2017/11/28.
 */

public class RecordTemplatePresenterImpl extends BasePresenterImpl<RecordTemplateContract.View> implements RecordTemplateContract.Presenter {
    private SlimAdapterEx adapter;
    private JSONArray header;
    private JSONArray body;
    private JSONArray config;
    private JSONArray actions;
    private int ScreenWidth;

    public RecordTemplatePresenterImpl(Context context, RecordTemplateContract.View view) {
        super(context, view);
        WindowManager manager = ((Activity) context).getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        ScreenWidth = outMetrics.widthPixels;
    }

    /**
     * 首次获取基本配置和数据
     */
    @Override
    public void start() {
        RecordTemplateModelImpl.getInstance(context)
                .getDatas(new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.getString("flag").equals("1")) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            body = data.getJSONArray("body");
                            header = data.getJSONArray("header");
                            config = data.getJSONArray("config");
                            actions = data.getJSONArray("actions");
                            view.finishLoadData();
//                            adapter.updateData(JSONUtil.JsonArray2List(body)).notifyDataSetChanged();
                            DataBaseUtil.saveJsonArrayData(context, BaseAction.class, data.getJSONArray("actions"));
                        } else {
                            Toast.makeText(context, jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    @Override
    public void bindRV(final RecyclerView recyclerView) {
        adapter = SlimAdapter.create(SlimAdapterEx.class)
                .enableDiff()
                .enableEmptyView(context, R.layout.empty_layout)
                .registerDefault(R.layout.record_item_layout, new SlimInjector<JSONObject>() {
                    @Override
                    public void onInject(final JSONObject data, IViewInjector injector) {
                        LinearLayout linearLayout = (LinearLayout) injector.findViewById(R.id.layout);
                        List<View> views = null;
                        if (linearLayout.getTag() == null) {
                            views = new ArrayList<>();
                            try {
                                for (int i = 0; i < header.length(); i++) {
                                    JSONObject jsonObject1 = header.getJSONObject(i);
                                    JSONObject titleConfig = jsonObject1.getJSONObject("config");
                                    if (titleConfig.getString("isShow").equals("0"))
                                        continue;
                                    if (jsonObject1.getString("type").equals("title")) {
                                        TextView textView = new TextView(context);
                                        textView.setGravity(Gravity.CENTER);
                                        textView.setWidth((int) (titleConfig.getDouble("titleWidth") * ScreenWidth));
                                        textView.setTextSize(14);
                                        textView.setTag(jsonObject1.getString("key"));
                                        views.add(textView);
                                        ViewGroup.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                                        linearLayout.addView(textView, layoutParams1);
                                        if (i != header.length() - 1) {
                                            ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(1, ViewGroup.LayoutParams.MATCH_PARENT);
                                            linearLayout.addView(getLine(), layoutParams);
                                        }
                                    } else if (jsonObject1.getString("type").equals("action")) {
                                        View delView = LayoutInflater.from(context).inflate(R.layout.delete_rel_icon_layout, null);
                                        delView.setTag(titleConfig.getString("actionName"));
                                        ViewGroup.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        linearLayout.addView(delView, layoutParams2);
                                        views.add(delView);
                                    }
                                }
                                linearLayout.setTag(views);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            views = (List<View>) linearLayout.getTag();
                        }
                        JSONArray values = null;
                        try {
                            values = data.getJSONArray("values");
                            for (int i = 0; i < views.size(); i++) {
                                final View view = views.get(i);
                                if (view instanceof TextView) {
                                    String keyStr = (String) view.getTag();
                                    for (int i1 = 0; i1 < values.length(); i1++) {
                                        JSONObject jsonObject = values.getJSONObject(i1);
                                        if (jsonObject.getString("key").equals(keyStr)) {
                                            ((TextView) view).setText(jsonObject.getString("value"));
                                            break;
                                        }
                                    }
                                } else {
                                    view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            try {
                                                TemplateHelper.doAction(context, view.getTag().toString(), data.getString("id"), "id", new WebService.NetSuccessListener() {
                                                    @Override
                                                    public void Success(String s) throws JSONException {
                                                        JSONObject jsonObject2 = new JSONObject(s);
                                                        if (jsonObject2.getInt("flag") == 1) {
                                                            Toast.makeText(context, jsonObject2.getString("data").toString(), Toast.LENGTH_SHORT).show();
                                                            refresh();
                                                        }
                                                    }
                                                });
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        adapter.attachTo(recyclerView);
        adapter.updateData(JSONUtil.JsonArray2List(body)).notifyDataSetChanged();
    }

    private ImageView getLine() {
        ImageView imageView = new ImageView(context);
        imageView.setBackgroundColor(Color.RED);
        return imageView;
    }


    //提交数据
    @Override
    public void upAction() {
        try {
            JSONObject jsonObject0 = new JSONObject();
            jsonObject0.put("pageid", SPUtils.getInstance().getString(BaseApplication.MODULETYPE));
            JSONArray ids = new JSONArray();
            for (int i = 0; i < body.length(); i++) {
                JSONObject bodyItem = body.getJSONObject(i);
                JSONObject itemJson = new JSONObject();
                itemJson.put("id", bodyItem.getString("id"));
                ids.put(itemJson);
            }
            jsonObject0.put("ids", ids);
            JSONObject jsonObject = actions.getJSONObject(1);
            new WebService.Builder(context, jsonObject.getString("actionName"), jsonObject.getString("space"))
                    .addProperty("jsonString", jsonObject0.toString())
                    .showDialog(true)
                    .success(new WebService.NetSuccessListener() {
                        @Override
                        public void Success(String s) throws JSONException {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("flag").equals("0")) {
                                Toast.makeText(context, jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();
                                refresh();
                            }
                        }
                    })
                    .post();


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void refresh() {
        RecordTemplateModelImpl.getInstance(context)
                .getDatas(new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.getString("flag").equals("1")) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            body = data.getJSONArray("body");
                            adapter.updateData(JSONUtil.JsonArray2List(body)).notifyDataSetChanged();
                            view.finshRefresh();
                        } else {
                            Toast.makeText(context, jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void setHeader(LinearLayout linearLayout) {
        linearLayout.setBackgroundColor(context.getResources().getColor(R.color.titleBgColor));
        for (int i = 0; i < header.length(); i++) {
            try {
                JSONObject jsonObject1 = header.getJSONObject(i);
                JSONObject titleConfig = jsonObject1.getJSONObject("config");
                if (titleConfig.getString("isShow").equals("1")) { //1 显示  0 不显示
                    TextView textView = new TextView(context);
                    textView.setGravity(Gravity.CENTER);
                    textView.setText(jsonObject1.getString("title"));
                    textView.setTextColor(Color.WHITE);
                    ViewGroup.LayoutParams layoutParams1 = null;
                    if (i == header.length() - 1) {
                        layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    } else {
                        textView.setWidth((int) (titleConfig.getDouble("titleWidth") * ScreenWidth));
                        layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    }
                    linearLayout.addView(textView, layoutParams1);
                    if (i != header.length() - 1) {
                        ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(1, ViewGroup.LayoutParams.MATCH_PARENT);
                        linearLayout.addView(getLine(), layoutParams);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
